package com.zjj.edu.web.controller.system;

import com.zjj.edu.common.annotation.Log;
import com.zjj.edu.common.constant.UserConstants;
import com.zjj.edu.common.core.controller.BaseController;
import com.zjj.edu.common.core.domain.AjaxResult;
import com.zjj.edu.common.core.page.TableDataInfo;
import com.zjj.edu.common.enums.BusinessType;
import com.zjj.edu.common.utils.poi.ExcelUtil;
import com.zjj.edu.framework.util.ShiroUtils;
import com.zjj.edu.system.domain.SysApplication;
import com.zjj.edu.system.domain.SysTenant;
import com.zjj.edu.system.domain.SysTenantApplication;
import com.zjj.edu.system.service.ISysApplicationService;
import com.zjj.edu.system.service.ISysTenantService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 租户信息
 * 
 * @author zjj
 */
@Controller
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController {
	private String prefix = "system/tenant";

	@Autowired
	private ISysTenantService tenantService;

	@Autowired
	private ISysApplicationService applicationService;

	@RequiresPermissions("system:tenant:view")
	@GetMapping()
	public String role() {
		return prefix + "/tenant";
	}

	@RequiresPermissions("system:tenant:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysTenant tenant) {
		startPage();
		List<SysTenant> list = tenantService.selectTenantList(tenant);
		return getDataTable(list);
	}

	@Log(title = "租户管理", businessType = BusinessType.EXPORT)
	@RequiresPermissions("system:tenant:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(SysTenant tenant) {
		List<SysTenant> list = tenantService.selectTenantList(tenant);
		ExcelUtil<SysTenant> util = new ExcelUtil<SysTenant>(SysTenant.class);
		return util.exportExcel(list, "租户数据");
	}
	

    @RequiresPermissions("system:tenant:remove")
    @Log(title = "租户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(tenantService.deleteTenantByIds(ids));
        }
        catch (Exception e) {
            return error(e.getMessage());
        }
    }


	/**
	 * 新增租户
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存租户
	 */
	@RequiresPermissions("system:tenant:add")
	@Log(title = "租户管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(@Validated SysTenant tenant) {
		String loginName = ShiroUtils.getLoginName();
		if (UserConstants.TENANT_NAME_NOT_UNIQUE.equals(tenantService.checkTenantNameUnique(tenant))) {
		   return error("新增租户'" + tenant.getTenantName() + "'失败，租户名称已存在");
		}
		if (UserConstants.TENANT_NAME_NOT_UNIQUE.equals(tenantService.checkTenantCodeUnique(tenant))) {
			return error("修改租户'" + tenant.getTenantName() + "'失败，租户编码已存在");
		}
		tenant.setCreateBy(loginName);
		int status = tenantService.insertTenant(tenant);
		long tenantId = tenant.getTenantId();

		List<String> appCodes = new ArrayList<>();
		appCodes.add("TenantUser");
		appCodes.add("TenantTeach");
		appCodes.add("TenantSystemSetting");
		SysTenantApplication sysTenantApplication = new SysTenantApplication();
		sysTenantApplication.setAppCodes(appCodes);
		sysTenantApplication.setTenantId(tenantId);
		tenantService.authApplication(sysTenantApplication, loginName);
		return toAjax((int) tenantId);
	}

	/**
	 * 校验租户名称
	 */
	@PostMapping("/checkTenantNameUnique")
	@ResponseBody
	public String checkTenantNameUnique(SysTenant tenant) {
		return tenantService.checkTenantNameUnique(tenant);
	}

	/**
	 * 校验租户编码
	 */
	@PostMapping("/checkTenantCodeUnique")
	@ResponseBody
	public String checkTenantCodeUnique(SysTenant tenant) {
		return tenantService.checkTenantCodeUnique(tenant);
	}

	/**
	 * 修改租户
	 */
	@GetMapping("/edit/{tenantId}")
	public String edit(@PathVariable("tenantId") Long tenantId, ModelMap mmap) {
		mmap.put("tenant", tenantService.selectTenantById(tenantId));
		return prefix + "/edit";
	}

	/**
	 * 修改保存租户
	 */
	@RequiresPermissions("system:role:edit")
	@Log(title = "租户管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(@Validated SysTenant tenant) {
		if (UserConstants.TENANT_NAME_NOT_UNIQUE.equals(tenantService.checkTenantNameUnique(tenant))) {
		   return error("修改租户'" + tenant.getTenantName() + "'失败，租户名称已存在");
		}
		if (UserConstants.TENANT_NAME_NOT_UNIQUE.equals(tenantService.checkTenantCodeUnique(tenant))) {
			return error("修改租户'" + tenant.getTenantName() + "'失败，租户编码已存在");
		}
		tenant.setUpdateBy(ShiroUtils.getLoginName());
		return toAjax(tenantService.updateTenant(tenant));
	}


	/**
	 * 分配应用
	 *
	 * @param tenantId
	 * @param mmap
	 * @return
	 */
	@GetMapping("/authApplication/{tenantId}")
	public String authApplication(@PathVariable("tenantId") Long tenantId, ModelMap mmap) {
		mmap.put("tenant", tenantService.selectTenantById(tenantId));

		// 获取所有可分配给租户的子系统
		List<SysApplication> applications = applicationService.selectApplicationsTenant();
		if (applications != null && applications.size() > 0) {
			// 判断哪些是选中状态
			List<SysTenantApplication> sysTenantApplications = tenantService.selectTenantApplicationByTenantId(tenantId);
			for (SysTenantApplication tenantApplication : sysTenantApplications) {
				for (SysApplication sysApplication : applications) {
					if (sysApplication.getAppCode().equals(tenantApplication.getAppCode())) {
						sysApplication.setFlag(true);
					}
				}
			}
		}
		mmap.put("applications", applications);
		return prefix + "/authApplication";
	}

	/**
	 * 保存分配应用
	 */
	@RequiresPermissions("system:tenant:edit")
	@Log(title = "租户分配应用", businessType = BusinessType.UPDATE)
	@PostMapping("/authApplication")
	@ResponseBody
	public AjaxResult authApplication(@RequestBody SysTenantApplication sysTenantApplication) {
		String loginName = ShiroUtils.getLoginName();
		tenantService.authApplication(sysTenantApplication, loginName);
		return success();
	}
}